<template>
	<view class="contacts-page">
		<!-- 2. 索引列表 -->
		<u-index-list
			:index-list="indexList" 
			:custom-nav-height="navBarHeight"
			:active-color="'#27BA6A'"
		>
			<view v-for="(group, index) in groupedContacts" :key="index">
				<u-index-anchor :text="group.letter" bgColor="#F5F5F5" height="50rpx"></u-index-anchor>
				<view
					class="list-item"
					v-for="(user,userIndex) in group.data"
					:key="user.userId"
					@click="navigateToUserProfile(user)"
				>
					<u-avatar :src="user.avatar" size="45" mode="aspectFill"></u-avatar>
					<view class="item-info">
						<text class="name">{{ user.phoneName }}</text>
						<text class="app-info">昵称: {{ user.appName }}</text>
					</view>
					<view class="item-action">
						<u-button
							v-if="user.relationType==1||user.relationType==3"
							type="success"
							size="mini"
							shape="circle"
							text="关注TA"
							:ripple="true" 
							ripple-bg-color="#909399"
							@click.native.stop="addFriend(user,index,userIndex)"
						></u-button>
						<text v-else-if="user.relationType==2" class="added-text">已关注</text>
						<text v-else-if="user.relationType==4" class="added-text">添加成功</text>
						<text v-else class="added-text">其他属性</text>
					</view>
				</view>
			</view>
		</u-index-list>
		
		<u-loading-page :loading="isLoading" loading-text="正在加载联系人..."></u-loading-page>
	</view>
</template>

<script>
// 引入模拟的API调用
import { getClientUserList, getClientFollow } from '@/request/api.js';
// 实际项目中，需要一个将汉字转换为拼音首字母的库，例如 pinyin-pro
// 由于这里无法引入外部库，我们创建一个简化的模拟函数
import { getPinyinInitial } from '@/utils/pinyin-helper.js'; // 假设你有一个这样的工具函数
import Contacts from "@/utils/contacts.js";//注意路径是否正确
const $contacts = new Contacts();

export default {
	data() {
		return {
			isLoading: false,
			navBarHeight: 44, // 自定义导航栏内容高度
			// 原始手机联系人数据 (来自您的需求)
			phoneContactsRaw: [ 
				{ "name": "张译尹", "phones": ["19851733062"] }
			],
			// 处理后用于显示的数据
			groupedContacts: [],
			indexList: [],
		};
	},
	onLoad() {
		if(this.$store.state.phoneContacs.length!==0 || uni.getStorageSync('phoneContacs').length!==0){
			this.groupedContacts = uni.getStorageSync('phoneContacs')
			return
		}
		// #ifdef APP
		//请求获取权限
		$contacts.needAuthorize((res) => {
		});
		
		this.getContacts()
		// #endif
		// #ifdef H5
		this.processContacts();
		// #endif
	},
	onPullDownRefresh(){
		console.log('下拉刷新被触发'); // 检查日志输出
		this.getContacts()
		setTimeout(()=>{
			uni.stopPullDownRefresh();
		},1000)
	},
	methods: {
		getContacts(){
			$contacts.readContacts().then(res => {
				console.log('联系人==================',res);
				const map = new Map();
				res.forEach(obj => {
					const key = obj.name;
					if (!map.has(key) || obj.phones.length > map.get(key).phones.length) {
						map.set(key, obj);
					}
				});
				this.phoneContactsRaw = Array.from(map.values());
				this.processContacts();
			})
		},

		// 主处理函数
		async processContacts() {
			this.isLoading = true;
			
			// 1. 模拟从手机获取通讯录
			// 在真实应用中，这里会调用 uni.getContacts 或原生插件
			const contacts = this.phoneContactsRaw;

			const enrichedContacts = [];

			for (const contact of contacts) {
				let appUser = null;
				// 2. 遍历联系人的每个电话号码，查询后端
				for (const phone of contact.phones) {
					// 清理电话号码格式
					const sanitizedPhone = phone.replace(/[-\s+]/g, '');
					
					try {
						// 3. 模拟调用API查询用户信息
						const res = await this.mockGetClientUserList({ phonenumber: sanitizedPhone });
						if (res.data.rows && res.data.rows.length > 0) {
							appUser = res.data.rows[0];
							break; // 找到一个匹配的用户就停止查询此联系人的其他号码
						}
					} catch (error) {
						console.error(`查询手机号 ${sanitizedPhone} 出错:`, error);
					}
				}
				
				// 4. 如果找到了匹配的应用内用户，则添加到待显示列表
				if (appUser) {
					enrichedContacts.push({
						phoneName: contact.name, // 通讯录中的名字
						phone:appUser.phonenumber,
						appName: appUser.nickName, // App内的昵称
						avatar: appUser.avatar,
						relationType: appUser.relationType,
						userId: appUser.userId,
					});
				}
			}

			// 5. 按拼音首字母分组和排序
			this.groupAndSortContacts(enrichedContacts);
			
			
			this.isLoading = false;
		},

		// 模拟后端API: 根据手机号查询用户
		mockGetClientUserList(params) {
			const data = {
				phonenumber: /^\d+$/.test(params.phonenumber) ? params.phonenumber : undefined,
				pageNum: 1,
				pageSize: 10,
			};
			
			return new Promise(resolve => {
				getClientUserList(data).then(res=>{
					resolve({
						data: {
							code: 200,
							rows: res.data.rows[0]&&res.data.rows[0].phonenumber==data.phonenumber ? res.data.rows : []
						}
					});
				});
			});
		},

		// 分组和排序联系人
		groupAndSortContacts(contacts) {
			// 添加拼音首字母
			contacts.forEach(contact => {
				contact.initial = getPinyinInitial(contact.phoneName);
			});

			// 排序
			contacts.sort((a, b) => a.initial.localeCompare(b.initial));

			const grouped = {};
			contacts.forEach(contact => {
				const letter = contact.initial;
				if (!grouped[letter]) {
					grouped[letter] = [];
				}
				grouped[letter].push(contact);
			});

			this.indexList = Object.keys(grouped).sort();
			this.groupedContacts = this.indexList.map(letter => ({
				letter: letter,
				data: grouped[letter]
			}));
			this.$store.commit('setPhoneContacs',this.groupedContacts);
		},

		// 添加朋友
		async addFriend(user,index,userIndex) {
			uni.showLoading({ title: '正在发送请求...' });
			try {
				// 模拟调用API
				getClientFollow({ userId: user.userId }).then(res=>{
					if(res.data.code!=500){
						uni.hideLoading();
						uni.showToast({ title: '好友请求已发送', icon: 'success' });
						// 更新UI状态
						
						if(this.groupedContacts[index].data[userIndex].relationType==1){
							this.groupedContacts[index].data[userIndex].relationType = 2
						}else{
							this.groupedContacts[index].data[userIndex].relationType = 4
						}
						
						console.log("this.groupedContacts",this.groupedContacts[index].data[userIndex]);
						this.$store.commit('setPhoneContacs',this.groupedContacts);
						this.$forceUpdate()
					}else{
						uni.showToast({
							title: "关注失败" ,
							icon: 'none',
						})
					}
				});
				
			} catch (error) {
				uni.hideLoading();
				uni.showToast({ title: '操作失败', icon: 'none' });
			}
		},
		navigateToUserProfile(user) {
			uni.navigateTo({ url: `/pages/user/others/others?userId=${user.userId}` });
		}
	}
};
</script>

<style lang="scss" scoped>
.contacts-page {
	height: 100vh;
	display: flex;
	flex-direction: column;
	background-color: #fff;
}

.nav-bar-container {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 99;
	background-color: #f8f8f8;
	border-bottom: 1rpx solid #e7e7e7;
}

.nav-bar-content {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 44px;
	padding: 0 30rpx;
}

.nav-bar-title {
	font-size: 34rpx;
	font-weight: bold;
	color: #303133;
}

.list-item {
	display: flex;
	align-items: center;
	padding: 20rpx 30rpx;
	border-bottom: 1rpx solid #f5f5f5;

	.item-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		margin-left: 24rpx;

		.name {
			font-size: 30rpx;
			color: #303133;
			font-weight: 500;
		}

		.app-info {
			font-size: 24rpx;
			color: #909399;
			margin-top: 4rpx;
		}
	}

	.item-action {
		.added-text {
			font-size: 28rpx;
			color: #909399;
		}
	}
}

// 覆盖 u-index-list 的一些默认样式
::v-deep .u-index-list__letter {
	color: #27BA6A;
}
::v-deep .u-index-anchor {
	font-size: 24rpx !important;
	color: #606266 !important;
}

</style>